<%@ page pageEncoding="UTF-8"%>
<%@ page import="java.util.Map.Entry,java.util.*,java.util.regex.*,java.net.*,java.io.*,java.text.*"%>
<%@ page import="com.tianxiabuyi.*,com.tianxiabuyi.db.*,com.tianxiabuyi.model.*,com.tianxiabuyi.util.*"%>
<%@ page import="org.jsoup.Jsoup,org.jsoup.nodes.Element,org.jsoup.select.Elements"%>
<%@ page import="com.google.gson.reflect.TypeToken"%>
<%@ page import="org.dom4j.*"%>
<%!
	// 查询用户名是否存在
	List userNames(String userName, Integer hospital) {
		return QBuilder.db("basedb").select().from("User").where(new Where("userName=", userName).and("status=", STATUS_ENABLE).and("hospital=", hospital)).page(1,1).query().getResultObj();
	}

	// 登录
	Message login(User user) {
		Message msg = new Message();
		if (null == user) {
			setErrcode(msg, LOGIN_FAILED);
			return msg;
		}
		String userName = user.getUserName();
		String password = user.getPassword();
		Integer hospital = user.getHospital();
		/*账号和密码错误*/
		List<User> users1 = QBuilder.db("basedb").select().from("User").where(new Where("userName=", userName).and("status=", STATUS_ENABLE).and("hospital=", hospital)).page(1,1).query().getResultObj();
		if (users1.size() == 0) { // 登录失败
			setErrcode(msg, LOGIN_FAILED);
			msg.put("errmsg" , "账号不存在");
			
			return msg;
		}
		List<User> users = QBuilder.db("basedb").select().from("User").where(new Where("userName=", userName).and("password=", password).and("status=", STATUS_ENABLE).and("hospital=", hospital)).page(1,1).query().getResultObj();
		if (users.size() == 0) { // 登录失败
			setErrcode(msg, LOGIN_FAILED);
			msg.put("errmsg" , "密码不正确");
			
			return msg;
		}

		// 设置最后登录时间和ip
		User u = users.get(0);
		user.setLastIp(Tools.getDesc(user.getJson("ip"), ""));
		user.setLastLogin(System.currentTimeMillis());
		Map userJson = u.getJson();
		userJson.put("ip", Tools.getDesc(user.getJson("ip"), ""));
		userJson.put("from", Tools.getDesc(user.getJson("from"), ""));
		userJson.put("token", Tools.getDesc(user.getJson("token"), ""));
		user.setJson(userJson);
		user.setUserName(u.getUserName());
		DBTools.db("basedb").modItem(user, u.getId());

		// 根据用户类型展示不同的信息
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		jsonMap.put("uid", u.getId());
		jsonMap.put("user_name", u.getUserName());
		jsonMap.put("name", u.getName());
		jsonMap.put("type", u.getType());
		jsonMap.put("role", u.getType());
		Integer userType = u.getType();
		jsonMap.put("type", userType + "");
		if (USER_PATIENT.equals(userType) || SIGN_PATIENT.equals(userType)) { // 普通用户
			setUserInfo(u, jsonMap);
		} else if(USER_EMPLOYEE.equals(userType) || SIGN_EMPLOYEE.equals(userType)) { // 医院员工
			setEmployeeInfo(u, jsonMap);
		}
		user.setId(u.getId());
		Map tokenMap = token(user);
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("token", tokenMap.get("token"));
		map.put("expires_in", tokenMap.get("expireIn"));
		msg.put("auth", GsonUtil.toJson(map));
		msg.put("user", jsonMap);
		return msg;
	}

	// 生成令牌
	public Map token(User user) {
		if (null == user) {
			return new HashMap();
		}
		Token token = new Token();
		token.setUid(user.getId());
		token.setStatus(STATUS_ENABLE);
		token.setUserName(user.getUserName());
		token.setPassword(user.getPassword());
		token.setHospital(user.getHospital());
		String from = Tools.getDesc(user.getJson("from"), "");
		if ("wechat".equals(from)) { // 微信用户
			token.setWechat(true);
			token.setExpireIn(-1);
			token.setToken(Tools.getDesc(user.getJson("token"), ""));
		}
		return token.genToken();
	}

	// 设置医院员工信息
	void setEmployeeInfo(User user, Map<String, Object> jsonMap) {
		jsonMap.put("employee_id", user.getEmployeeId());
		jsonMap.put("avatar", Tools.getDesc(user.getAvatar(), EMPLOYEE_AVATAR_M));
		jsonMap.put("gender", Tools.getDesc(user.getGender() + "", ""));
		jsonMap.put("title", Tools.getDesc(user.getTitle(), ""));
		jsonMap.put("skill", Tools.getDesc(user.getJson("skill"), ""));
		jsonMap.put("specialty", Tools.getDesc(user.getJson("specialty"), ""));
		jsonMap.put("state", Tools.getDesc(user.getJson("state"), ""));
		jsonMap.put("mail", Tools.getDesc(user.getMail(), ""));
		jsonMap.put("hospital_name", Tools.getDesc(user.getJson("hospital_name"), ""));
		jsonMap.put("dept", Tools.getDesc(user.getJson("dept"), ""));
		jsonMap.put("certification", Tools.getDesc(user.getJson("certification"), ""));
		jsonMap.put("phone", Tools.getDesc(user.getPhone() + "", ""));
		jsonMap.putAll(user.getJson());
		// 查找所在科室信息
		Integer deptId = user.getDeptId();
		List<Dept> employeeDepts = QBuilder.db("basedb").queryHql("from Dept where id=" + deptId);
		if (employeeDepts.size() > 0) {
			Dept eDept = employeeDepts.get(0);
			String employeeDeptId = eDept.getDeptId();
			String employeeDeptName = eDept.getDeptName();
			jsonMap.put("dept_id", employeeDeptId);
			jsonMap.put("dept_name", employeeDeptName);
		}
	}

	// 设置普通用户信息
	void setUserInfo(User user, Map<String, Object> jsonMap) {
		jsonMap.put("avatar", Tools.getDesc(user.getAvatar(), USER_AVATAR_M));
		jsonMap.put("city", Tools.getDesc(user.getCity(), ""));
		// 查找用户信息
		Integer uid = user.getId();
		List<UserProfile> userProfiles = QBuilder.db("basedb").queryHql("from UserProfile where uid=" + uid + " and self != " + FAMILY);
		if (userProfiles.size() > 0) {
			UserProfile userProfile = userProfiles.get(0);
			if (userProfile.getBirthday() == null) {
				jsonMap.put("birthday", "");
			} else {
				Long birth = Tools.getLong(userProfile.getBirthday() + "", -1L);
				jsonMap.put("birthday", DateUtil.formatDate(new Date(birth)));
			}
			jsonMap.put("gender", Tools.getDesc(userProfile.getGender() + "", ""));
			jsonMap.put("self", Tools.getDesc(userProfile.getSelf() + "", "0"));
			jsonMap.put("age", Tools.getDesc(userProfile.getAge() + "", ""));
			jsonMap.put("phone", Tools.getDesc(userProfile.getPhone() + "", ""));
			jsonMap.put("card_type", Tools.getDesc(userProfile.getCardType() + "", ""));
			jsonMap.put("card_number", Tools.getDesc(userProfile.getCardNumber() + "", ""));
			jsonMap.put("medical_type", Tools.getDesc(userProfile.getMedicalType() + "", ""));
			jsonMap.put("medical_number", Tools.getDesc(userProfile.getMedicalNumber() + "", ""));
			jsonMap.put("patient_id", Tools.getDesc(userProfile.getPatientId() + "", ""));
			jsonMap.put("json", userProfile.getJson());
		}
	}


	//注册
	public Message register(User user, UserProfile userProfile) {
		Message msg = new Message("注册成功");
		int hospital = user.getHospital();
		String userName = Tools.getDesc(user.getUserName());
		String password = Tools.getDesc(user.getPassword());
		String passwd = Tools.getDesc(user.getRepassword());
		if (userName.length() < 4){ //用户名长度不合法
			setErrcode(msg, USERNAME_ILLEGAL_LENGTH);
			return msg;
		}
		String match = "[a-zA-Z0-9_]*";
		if (!userName.matches(match)) { //用户名以字母或下划线开头
			setErrcode(msg, USERNAME_ILLEGAL);
			return msg;
		}
		if (password.length() < 4) { //密码长度不合法
			setErrcode(msg, PASSWORD_ILLEGAL_LENGTH);
			return msg;
		}
		if (!password.matches(match)) { //密码不能包含非法字符
			setErrcode(msg, PASSWORD_ILLEGAL);
			return msg;
		}
		if (!passwd.equals(password)) { //两次密码不一致
			setErrcode(msg, PASSWORD_DIFF);
			return msg;
		}
		List<User> list = QBuilder.db("basedb").select().from("User as u").where(new Where("u.userName=", userName).and("u.status=", STATUS_ENABLE).and("u.hospital=", hospital)).page(1, 1).query().getResultObj();

		if (list.size() > 0) { //用户已经存在
			setErrcode(msg, USER_EXITS);
			return msg;
		}
		if (!SIGN_PATIENT.equals(user.getType()) && !SIGN_EMPLOYEE.equals(user.getType()) && !USER_EMPLOYEE.equals(user.getType())) {
			user.setType(USER_PATIENT);
		}
		String lastIp = Tools.getDesc(user.getJson("ip"), "");
		user.setLastIp(lastIp);
		user.setLastLogin(System.currentTimeMillis());
		user.setCity((user.getCity() == null || user.getCity() == 0) ? 510 : user.getCity());
		Integer uid = (Integer)DBTools.db("basedb").addItem(user);

		userProfile.setUid(user.getId());
		userProfile.setName(user.getName());
		userProfile.setSelf(SELF); // 本人账户
		DBTools.db("basedb").addItem(userProfile);

		Map map = token(user);
		msg.put("uid", uid);
		return msg;
	}

	// 根据uid查询用户信息
	User userByUid (Integer uid) {
		List<Integer> uids = new ArrayList<Integer>();
		uids.add(uid);
		Map<Integer, User> map =  usersByUids(uids);
		User user =  Tools.getObject(map.get(uid), null);
		return user;
	}

	// 根据所给uid查询对应的用户信息
 	Map<Integer, User> usersByUids(List<Integer> uids) {
		if (uids == null) return new HashMap<Integer, User>();
		StringBuffer buffer = new StringBuffer();
		for (int i = 0; i < uids.size(); i++) {
			Integer uid = uids.get(i);
			buffer.append(uid + ",");
		}

		if (buffer.length() == 0) return new HashMap<Integer, User>();
		String allUid = buffer.toString();
		if (allUid.endsWith(",")) {
			allUid = allUid.substring(0, allUid.length() - 1);
		}
		List<User> users = QBuilder.db("basedb").queryHql("from User where id in (" + allUid + ")");
		Map<Integer, User> map = new HashMap<Integer, User>();
		for (int i = 0; i < users.size(); i++) {
			User user = users.get(i);
			Integer uid = user.getId();
			map.put(uid, user);
		}
		return map;
	}

	/**
	 * 附二院更新到内网的数据（部分数据同步）
	 * @param user
	 * @param up
	 * @return
	 */
	Map<String, String>  updateUser(User user,UserProfile up){
		Map<String, String> map = new HashMap<String, String>();
		map.put("user_name",user.getUserName());
		map.put("password",user.getPassword());
		map.put("name",user.getName());
		map.put("hospital",user.getHospital()+"");
		map.put("cTime",user.getcTime()+"");
		map.put("json",user.getJsonString());
		map.put("type",user.getType()+"");
		map.put("phone",user.getPhone());

		//用户详细信息
		map.put("card_type",up.getCardType());
		map.put("card_number",up.getCardNumber());
		map.put("medical_type",up.getMedicalType());
		map.put("self",up.getSelf()+"");
		map.put("age",up.getAge()+"");
		//发送请求
		String url = "http://221.224.34.163:7071/user/update.jsp";
        HttpUtil.post(url, map);

		return map;
	}
%>
